package com.molyfun.core.resolvers;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.support.MissingServletRequestPartException;

import com.molyfun.core.annotation.CurrentUser;
import com.molyfun.model.user.HoUser;
import com.molyfun.service.user.HoUserServiceImpl;

/**
 * 增加方法注入，将含有CurrentUser注解的方法参数注入当前登录用户
 * @author shidongsheng
 */
public class CurrentUserMethodArgumentResolver implements HandlerMethodArgumentResolver {

    @Autowired
    private HoUserServiceImpl userService;
    
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if (parameter.getParameterType().isAssignableFrom(HoUser.class) &&
				parameter.hasParameterAnnotation(CurrentUser.class)) {
			return true;
		}
		return false;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		String  userId = (String) webRequest.getAttribute("userId", RequestAttributes.SCOPE_REQUEST);
        if (userId != null) 
        {
    		return this.userService.queryById(userId);
        }
        throw new MissingServletRequestPartException("userId");
	}
}
